import openai
from datetime import datetime, timedelta

# openai.api_key = "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"
# openai.api_key = "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"
# openai.api_key = "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"
# openai.api_key = "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"
openai.api_key = "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"
completion = openai.ChatCompletion()
chat_log = dict()
last_active = dict()


def init_chat_log(user, chat_log):
    chat_log[user] = [{"role": "system", "content": "我希望你扮演金融报告文档写作者。我将提供一些关于这份报告的相关资料，比如公司的基本信息，报告的写作类型，关于项目的材料数据，等等，你将根据这些材料来编写这份报告或者文档。这可能包括生成各种表格或流程图，要根据具体语境来进行编写和创作。"}]
    last_active[user] = datetime.now()


def append_interaction_to_chat_log(user, question, answer, chat_log):
    if not user in chat_log:
        init_chat_log(user, chat_log)
    chat_log[user].append({"role": "assistant", "content": answer})
    last_active[user] = datetime.now()
    return chat_log


def ask(user, question, chat_log, isGpt_4):
    if not user in chat_log:
        init_chat_log(user, chat_log)
    now = datetime.now()
    difference = now - last_active[user]
    difference_in_minutes = difference.total_seconds() / 60
    if difference_in_minutes > 15:
        init_chat_log(user, chat_log)
    chat_log[user].append({"role": "user", "content": question})
    prompt = chat_log[user]
    response = completion.create(
        model="gpt-4-32k" if isGpt_4 else "gpt-3.5-turbo-16k",
        messages=prompt
    )
    answer = response['choices'][0]['message']['content']
    chat_log = append_interaction_to_chat_log(user, question, answer, chat_log)
    return answer


def reset_chat_log(chat_log, user=None):
    if user is None:
        chat_log.clear()
    else:
        chat_log.pop(user)
    return chat_log

